#!/usr/bin/python
#coding=utf-8
import logging
import os
import sched
import time
import sys

__author__ = 'bjxiajun'
__version__= '1.0.0'
__date__='2013-07-20'
class TimerTask:
    u"""
        一个简单的定时任务 一天 86400s 一周 604800s
        nohup ./TimerTask.py >/dev/null 2>&1 &
    """
    schedule = sched.scheduler(time.time, time.sleep)
    log = logging.getLogger()
    handler = logging.FileHandler("timer.log")
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    handler.setFormatter(formatter)
    handler2 = logging.StreamHandler()
    handler2.setFormatter(formatter)
    log.addHandler(handler2)
    log.addHandler(handler)
    log.setLevel(logging.INFO)

    def __init__(self):
        self.date_ = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        self.oldDate = time.strftime('%Y-%m-%d', time.localtime(time.time() - 86400))

    def performCommand(self,pos):
        rebate_ = time.strftime('%Y-%m-%d', time.localtime(time.time() - 3888000))
        cmd = self.readCmd(rebate_);
        #self.schedule.enter(inc, 0, self.performCommand, (inc,))
        self.log.info("=======================start=========================")
        for i,v in enumerate(cmd):
            if i < pos:
                continue
            res = os.system(v)
            #res=0
            #print i
            if res == 0:
                self.log.info(u"%r 执行成功.", v)
            else:
                self.log.info(u"%r 执行失败.", v)
        self.log.info("=========================end=========================")

    def exe(self,pos):
        u"""执行命令 cmd:命令，tim:开始运行时间，inc:运行间隔时间"""
        #print tim
        #if cmp(tim,"0")==0:
        #    lazy_time=0
        #else:
		#	current_time = time.time()
		#	time_ = self.date_ + " " + tim
		#	run_time = time.mktime(time.strptime(time_, "%Y-%m-%d %H:%M:%S"))
		#	lazy_time = run_time - current_time
        #if lazy_time < 0:
        #    self.log.warning(
        #        u"定时运行时间已过将在明天触发程序,现在是 %s", str(time.strftime("%H:%M:%S", time.localtime(time.time()))))
        #    lazy_time2 = (run_time + (24 * 3600)) - current_time
        #    self.schedule.enter(lazy_time2, 0, self.performCommand, (inc,))
        #else:
        #    self.log.info(u"等待%s秒后运行执行", lazy_time)
        #    self.schedule.enter(lazy_time, 0, self.performCommand, (inc,))
        #self.schedule.run()
        self.performCommand(pos)
    def readCmd(self,rdate=""):
        u"""
        读取文件中的命令
        rdate 运行时的日期
        """
        cmd_file=open("cmd.txt");
        cmd=[];
        cmd_str=""
        while True:
            line=cmd_file.readline()
            if not line:
                break
            if line.startswith('-- '):
                continue
            line=line.replace("\n","").replace("\r","").replace("%rdate%",rdate)+" "
            if cmp(line.replace(" ",""),"$$")==0:
                cmd.append(cmd_str)
                cmd_str=""
                line=""
            cmd_str+=line;
        cmd_file.close()
        return cmd

if __name__ == '__main__':
    tt = TimerTask()
    os.environ['HADOOP_HOME'] = '/home/mart_bda/hadoop'
    #tt.log.info("pid: %s",os.getpid())
    #if len(sys.argv)<2:
    #    print u"命格式为: ./TimerTask.py  12:00:00 (参数为开始运行时间)"
    #    exit(1)
    #if cmp(sys.argv[1],"-help")==0:
    #    print u"args 1. 开始运行时间[必须],2.运行间隔周期[可选]秒"
    #start_time= sys.argv[1]
    #if len(sys.argv)==3:
    #    round=sys.argv[2]
    #    round=int(round)
    #    tt.exe(start_time,round)
    #else:
    #    tt.exe(start_time)
    pos=0
    if len(sys.argv)==2:
        pos=int(sys.argv[1])
    tt.exe(pos)
